package com.pj.android.brower.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.*
import com.pj.android.brower.MyApplication
import com.pj.android.brower.R
import com.pj.android.brower.business.AndroidForJs
import com.pj.android.brower.common.Event.InvokeScriptEvent
import com.pj.android.brower.common.LocationManager
import com.pj.android.brower.ui.zbar.CaptureActivity
import com.pj.android.brower.util.Config
import com.pj.android.brower.util.Constants
import com.pj.android.brower.util.MetaInfUtils
import com.pj.android.relief.base.async.RxBus
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_main.*

class WebActivity : BaseActivity() {
    private val SCAN_CODE = 100
    private var scanCallBackName: String = ""
    private var scanSn: String = ""
    private var url: String? = ""

    var isShow = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(tool_bar.toolBar)
        initView()
        registerEvent()
    }


    private fun initView() {
        MyApplication.addActivity(this)
        url = intent.getStringExtra("url")
        if (url == null || url == "") {
            /** 获取主服务器地址 **/
            if (Config.instance.mainUrl == Constants.defaultUrl) {
                val updateInfo = MetaInfUtils.getUpdatePackage(this)
                if (updateInfo != null) {
                    Config.instance.mainUrl = updateInfo.url
                    Log.i("GlobalService", "读取到的地址：${Config.instance.mainUrl}")
                }
            }
            url = Config.instance.mainUrl
        }

        my_web.webViewClient = object : WebViewClient() {
            override fun onPageStarted(p0: WebView?, p1: String?, p2: Bitmap?) {
                super.onPageStarted(p0, p1, p2)
                showProcess()
            }

            override fun onPageFinished(p0: WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
                closeProcess()
            }
        }

        load()
    }

    override fun onResume() {
        super.onResume()
        isShow = true
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        supportActionBar?.setDisplayShowTitleEnabled(false) //设置不显示系统toolBarTitle
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SCAN_CODE && resultCode == Activity.RESULT_OK) {
            val bundle = data!!.extras
            val result = bundle.getString(CaptureActivity.EXTRA_STRING)
            val args = arrayOf(this.scanSn, result)
            runJs(this.scanCallBackName, args)
        }
    }

    private fun load() {
        my_web.addJavascriptInterface(AndroidForJs(this), "android")
        my_web.loadUrl(url)
    }

    fun showTitle(title: String) {
        runOnUiThread {
            tool_bar.title = title
            tool_bar.visibility = View.VISIBLE
        }
    }

    fun hiddenTitle() {
        runOnUiThread {
            tool_bar.visibility = View.GONE
        }
    }

    fun runJs(funName: String, parames: Array<String>) {
        runOnUiThread {
            val jsString = buildJsParamsString(parames)
            my_web.evaluateJavascript("javascript:$funName$jsString", object : ValueCallback<String> {
                override fun onReceiveValue(p0: String?) {
                }
            })
        }
    }


    override fun onPause() {
        super.onPause()
        isShow = false
    }


    private fun registerEvent() {
        RxBus.default.register(this, InvokeScriptEvent::class.java).observeOn(AndroidSchedulers.mainThread()).subscribe { result ->
            runJs(result.functionName, result.args)
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //重写返回键为网页的返回
        if (keyCode == KeyEvent.KEYCODE_BACK && my_web.canGoBack()) {
            my_web.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun scanQrCode(callBackName: String, sn: String) {
        this.scanCallBackName = callBackName
        this.scanSn = sn

        val intent = Intent(this, CaptureActivity::class.java)
        startActivityForResult(intent, SCAN_CODE)
    }

    /**
     * 构建js参数字符串
     */
    private fun buildJsParamsString(args: Array<String>): String {
        val sb = StringBuffer("(")
        args.forEach {
            sb.append("'$it'")
            sb.append(",")
        }
        val a = sb.toString().substring(0, sb.toString().length - 1)
        val sb1 = StringBuffer(a)
        sb1.append(")")
        return sb1.toString()
    }
}
